package com.gt.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSONObject;

/**
 * URLpost请求方法
 * @author zhangyu
 *
 */
public class URLConnectionUtil {

	/**
	 * 开放平台接口的请求方法
	 **/
	public String readContentFromPost(String url,String requestCode,String platform, String params) throws IOException {
		String Result = "";
		// Post请求的url，与get不同的是不需要带参数
		URL postUrl = new URL(url);
		// 打开连接
		HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
		
		// 设置是否向connection输出，因为这个是post请求，参数要放在
		// http正文内，因此需要设为true
		connection.setDoOutput(true);
		// Read from the connection. Default is true.
		connection.setDoInput(true);
		// 默认是 GET方式
		connection.setRequestMethod("POST");
		
		// Post 请求不能使用缓存
		connection.setUseCaches(false);
		
		connection.setInstanceFollowRedirects(true);
		// 配置本次连接的Content-type，配置为application/x-www-form-urlencoded的
		// 意思是正文是urlencoded编码过的form参数，下面我们可以看到我们对正文内容使用URLEncoder.encode
		// 进行编码
		connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		// 连接，从postUrl.openConnection()至此的配置必须要在connect之前完成，
		// 要注意的是connection.getOutputStream会隐含的进行connect。
		connection.connect();
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		// The URL-encoded contend
		// 正文，正文内容其实跟get的URL中 '? '后的参数字符串一致
		String content = "requestCode=" + URLEncoder.encode(requestCode, "UTF-8");
		content +="&platform="+URLEncoder.encode(platform, "UTF-8");
		
//		JSONObject params = new JSONObject();
//		params.put("orgCode", "91650100560549368P");
		
		content +="&params="+URLEncoder.encode(params, "UTF-8");
		
		// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
		out.writeBytes(content);
		out.flush();
		out.close();
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String line= "";
		while ((line = reader.readLine()) != null){
			System.out.println(line);
			Result = line;
		}
//		reader.close();
//		connection.disconnect();
		return Result;
	}
	
	public static void PostAccess(){
		// TODO Auto-generated method stub
    	PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL("http://192.168.30.231:8100/gtop/gt/inside.action");
//            URL realUrl = new URL("http://192.168.100.123:81/gtop/gt/inside.action");
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            String param = null;
    		
//            param = "requestCode=SYS_GT_PERSONNEL_GET_ORGID&platform=gtop&params={\"orgCode\":\"91650100560549368P\"}";
            param = "requestCode=SYS_BRANCHES_GET_ALL_SIMPLE_FOR_HR&platform=gtop&params={'orgId':'181'}";
//            param = "requestCode=SYS_ROLE_LIST&platform=gtop&params={'orgId':'181'}";
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println(result);
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
	}
	
	public static void main(String[] args) {

		
		
		
	}

}
